<template>
  <div class="kva-container">
    <div class="kva-contentbox">
      <home-page-header>

        <div class="kva-form-search">
          <el-form class="search-form" :inline="true" :model="queryParams" ref="searchForm">

            <el-form-item prop="keyword" label="权益名称：">
              <el-input v-model="queryParams.keyword" placeholder="权益名称" maxlength="100" clearable/>
            </el-form-item>
            <el-form-item>
              <el-button type="success" icon="Search" @click.prevent="handleSearch">搜索</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="danger" icon="Refresh" @click.prevent="handleReset">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-container style="border-radius: 8px;margin-top: 10px;background: #fff;">
          <el-main style="--el-main-padding:10px;">
            <div style="margin-bottom: 5px" v-if="showAlert">
              <el-alert @close="handleAlertClose" :title="'选中了（'+selectIds.length+'）项数据'" type="success" show-icon/>
            </div>
            <div style="margin: 0 0 10px;display: flex;justify-content: space-between">
              <div>
                <el-button type="primary" icon="Plus" :loading="tableLoading" @click="handleAdd">添加会员权益</el-button>
<!--                <el-button type="success" icon="Open" :loading="upLoading" @click="handleBatchStatus('up')">批量启用</el-button>
                <el-button type="warning" icon="Open" :loading="downLoading" @click="handleBatchStatus('down')">批量禁止</el-button>-->
                <el-button type="danger" icon="close" :loading="delLoading" @click="handleBatchRemoves()">批量删除
                </el-button>
              </div>
            </div>

            <el-table ref="tableRef"
                      @selection-change="handleSelectionChange"
                      v-loading="tableLoading"
                      :data="tableData" stripe border
                      :height="tableHeight">
              <el-table-column fixed type="selection" align="center" width="55"/>
              <el-table-column fixed :label="'总数：' + total" width="120" align="center">
                <template v-slot='scope'>
                  <span>{{ scope.$index + 1 }}</span>
                </template>
              </el-table-column>
              <el-table-column fixed label="权益名称" align="center" prop="title"></el-table-column>
              <el-table-column fixed label="状态" align="center" prop="status">
                <template #default="scope">
                  <div v-show="scope.row.status === 0">未发布</div>
                  <div v-show="scope.row.status === 1">已发布</div>
                </template>
              </el-table-column>
              <el-table-column fixed label="权益描述" align="center" prop="description"></el-table-column>
              <el-table-column fixed label="创建时间" prop="createTime" align="center" :formatter="formatDate">
              </el-table-column>
              <el-table-column fixed label="更新时间" prop="updateTime" align="center" :formatter="formatDate">
              </el-table-column>
              <el-table-column fixed="right" label="操作" align="center" width="200">
                <template #default="scope">
                  <el-button icon="edit" type="primary" size="small" @click.stop="handleEdit(scope.row)">编辑</el-button>
                  <el-button icon="remove" type="danger" size="small" @click.stop="handleDel(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="kva-pagination-box center">
              <el-pagination :current-page="queryParams.pageNo" :page-size="queryParams.pageSize"
                             layout="total, sizes, prev, pager, next, jumper" :total="total"
                             @size-change="handleSizeChange"
                             @current-change="handleCurrentChange"/>
            </div>
          </el-main>
        </el-container>
      </home-page-header>
      <add-authority ref="addRef" @load="handleLodeData"></add-authority>
    </div>
  </div>
</template>

<script setup>
import AddAuthority from './components/AddAuthority.vue'
import KVA from '@/utils/kva.js'
import {findPages,removeById,batchRemoves} from '@/api/users/benenfit.js'
import {findAuthorityList, updateStatus,batchDowns ,batchUps} from '@/api/userauthority.js'
// 搜索属性定义
const queryParams = reactive({
  pageNo: 1,
  pageSize: 30,
  permissionType: "",
  relationFlag: "",
  status: "",
  keyword: ""
})

const domain = ref("")
// 定义响应式得列表数据容器
const tableData = ref([])
const tableHeight = ref("calc(100vh - 315px)")
const tableLoading = ref(false)
const delLoading = ref(false)
const downLoading = ref(false)
const upLoading = ref(false)
const showAlert = ref(false)
const selectIds = ref([])
const selectOpIds = ref([])
const pages = ref(0)
const total = ref(0)
const searchForm = ref({})
const tableRef = ref({})
// 编辑添加相关
const addRef = ref({})
const authorityList = ref([])
// 加载数据
const handleLodeData = async () => {
  tableLoading.value = true
  const resp = await findPages(queryParams)
  tableLoading.value = false
  tableData.value = resp.data.records
  total.value = resp.data.total * 1
  pages.value = resp.data.pages * 1
}

// 搜索
const handleSearch = () => {
  queryParams.pageNo = 1
  handleLodeData()
}

// 重置
const handleReset = () => {
  searchForm.value.resetFields()
  handleSearch()
}

// 分页size更改
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  handleLodeData()
}

// 分页pageNo更改
const handleCurrentChange = (pno) => {
  queryParams.pageNo = pno
  handleLodeData()
}

// 添加事件
const handleAdd = () => {
  addRef.value.handleOpen(null, authorityList.value)
}

// 编辑
const handleEdit = (row) => {
  addRef.value.handleOpen(row.id, authorityList.value)
}

// 删除
const handleDel = (row) => {
  KVA.confirm("警告", "<strong>您确定要执行此次操作吗？</strong>", {icon: "success"}).then(async () => {
    const opid = row.id
    await removeById(opid)
    KVA.notifySuccess("删除成功!")
    handleLodeData()
  })
}


// 更新状态
const handleStatus = async (row, field) => {
  try {
    const res = await updateStatus(row.id, field, row[field])
    if (res.code == 20000) {
      KVA.notifySuccess("操作成功!")
      handleLodeData()
    }
  } catch (e) {
    handleLodeData()
  }
}

// 清空选择
const handleAlertClose = () => {
  showAlert.value = false;
  tableRef.value.clearSelection();
}


/**
 * 选择删除的元素
 * @param rows
 */
const handleSelectionChange = (rows) => {
  selectIds.value = rows.map(c => c.id)
  selectOpIds.value = rows.map(c => c.socialId)
  showAlert.value = rows.length > 0
  tableHeight.value = rows.length > 0 ? "calc(100vh - 355px)" : "calc(100vh - 315px)"
}


/**
 * 批量删除
 */
const handleBatchRemoves = async () => {
  if (selectIds.value.length == 0) {
    KVA.warning("请选择一项进行操作!")
    return;
  }

  KVA.confirm("警告", "<strong>您确定要执行【批量删除】吗？，一旦执行无法恢复！</strong>", {icon: "success"}).then(async () => {
    delLoading.value = true
    await batchRemoves(selectIds.value.join(','), selectOpIds.value.join(','))
    delLoading.value = false
    KVA.notifySuccess("批量删除成功!")
    handleLodeData()
  })
}

/**
 * 批量上下架
 */
const handleBatchStatus = async (field) => {
  if (selectIds.value.length == 0) {
    KVA.warning("请选择一项进行操作!")
    return;
  }
  if (field == 'up') {
    upLoading.value = true;
    await batchUps(selectIds.value.join(','), selectOpIds.value.join(','))
    upLoading.value = false;
  } else {
    downLoading.value = true;
    await batchDowns(selectIds.value.join(','), selectOpIds.value.join(','))
    downLoading.value = false;
  }
  KVA.notifySuccess("执行成功!")
  handleLodeData()
}




const formatDate = (row, column) => {
  const date = new Date(row.createTime);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  const seconds = date.getSeconds().toString().padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

onMounted(() => {
  handleLodeData()
})


</script>
